import { Modal, Row, Col } from "antd";
import React, { useState, forwardRef, useEffect, useRef } from "react";
import { Tabs } from "antd";
import dict from "./dict";
import styles from "./index.less";
import { getMathField } from "./helper";
import emitter from "../emitter";

const transLatex = (str, type = "toMathQuill") => {
  // 将标准的latex转为MathQuill格式的
  if (type == "toMathQuill") {
    return str
      .replace(
        /(\\x(?:longequal|rightarrow|leftrightharpoons))(?:\[([\s\S]*?)\])?{([\s\S]*?)}/g,
        (_, latexCmd, down, up) => `${latexCmd}{${up}}{${down || "\\ "}}`
      )
      .replace(/\\hfill/g, "");
  }
};

const App = (props, ref) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [content, setContent] = useState("");
  const mqRef = useRef(null);
  const [mathField, setMathField] = useState(null);
  const [mathQuillContent, setMathQuillContent] = useState("");

  useEffect(() => {
    emitter.on("openFormulaModal", (params: string = "") => {
      setIsModalOpen(true);
      setTimeout(() => {
        // setIsModalOpen是异步
        // 打开弹窗再初始化MathQuill
        const mathFieldObj: any = getMathField(mqRef.current, {
          edit: () => {
            setContent(mathFieldObj.latex()); //这里取到的都是标准的latex
            // 设置不标准的
            setMathQuillContent(transLatex(mathFieldObj.latex()))
          },
        });

        // mathquill的公式代码和katex不同
        mathFieldObj.latex(transLatex(params));
        setMathField(mathFieldObj);
      });
    });
  }, []);

  /*
   * 弹窗确定按钮点击
   */
  const handleOk = () => {
    console.log(content);

    props.editor.commands.insertContent(`<formula>${content}</formula>`);
    setIsModalOpen(false);
  };

  const [currentTab, setCurrentTab] = useState(dict[0].key);
  const onTabChange = (e) => {
    setCurrentTab(e);
  };

  /*
   * 公式元素显示组件
   * @param {Letter} letters - 公式集
   */
  const FormulaItem = ({ letters, type }) => {
    return (
      <div className={styles.mathIcon}>
        {letters.map((letter) => {
          const { remark, icon, overStyle = {}, wrapperStyle = {} } = letter;
          return (
            <div key={letter.latex}>
              <div
                className={styles.wrapper}
                title={remark}
                style={wrapperStyle}
                key={letter.latex}
                onClick={() => {
                  const mathQuillRes = transLatex(letter.latex);
                  setMathQuillContent(mathQuillContent+" "+mathQuillRes);
                  mathField.latex(mathQuillContent+" "+mathQuillRes);

                  // 存标准的
                  const res = content + " " + letter.latex;
                  setContent(res);
                  //
                }}
              >
                <img
                  className={styles.formulaItem}
                  style={overStyle}
                  src={icon}
                  alt={remark}
                />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <Modal
      title="插入公式"
      open={isModalOpen}
      onOk={handleOk}
      cancelText="取消"
      okText="确认"
      width={900}
      onCancel={() => {
        setIsModalOpen(false);
      }}
      mask={false}
      afterClose={() => {
        props.editor.commands.focus();
      }}
    >
      <div className={styles.PresetModal}>
        <Tabs
          onChange={onTabChange}
          items={dict.map((item: any) => {
            if (item.content) {
              item.children = (
                <FormulaItem letters={item.content} type={item.key} />
              );
            } else if (item.child) {
              item.children = (
                <div className={styles.mathIcon}>
                  {item.child.map((it) => {
                    return (
                      <section className={styles.specialSymbol} key={it.key}>
                        <Row>
                          <Col flex="120px">{it.label}</Col>
                          <Col flex="atuo">
                            <FormulaItem letters={it.content} type={it.key} />
                          </Col>
                        </Row>
                      </section>
                    );
                  })}
                </div>
              );
            }
            return item;
          })}
        />
      </div>
      <div className={styles.FormulaView}>
        <span ref={mqRef} />
      </div>
    </Modal>
  );
};

export default forwardRef(App);
